<template>
  <q-page class="cc-admin row">
    <div class="col bg-white shadow-2 q-ma-sm">
      <div class="row">
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>姓名：</q-item-label>
          <q-item-section>
            <q-input dense outlined v-model="searchForm.realname"></q-input>
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>电话：</q-item-label>
          <q-item-section>
            <q-input dense outlined v-model="searchForm.phone"></q-input>
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-section>
            <div class="row justify-center">
              <q-btn
                unelevated
                class="q-mr-sm no-border-radius"
                color="primary"
                icon="search"
                label="查询"
                :loading="loading"
                @click="query()"
              />
              <q-btn
                no-wrap
                outline
                unelevated
                class="q-mr-sm no-border-radius"
                color="secondary"
                icon="refresh"
                label="重置"
                @click="searchReset"
              />
            </div>
          </q-item-section>
        </q-item>
      </div>
      <q-table
        flat
        color="primary"
        class="cross_table"
        separator="cell"
        :columns="columns"
        :data="list"
        row-key="id"
        :pagination.sync="pagination"
        :visible-columns="group"
        @request="query"
        :rows-per-page-options="[10,20,50,100]"
        :selection="mobile?'none':'multiple'"
        :selected.sync="selected"
      >
        <template #top-right="table">
          <table-top-btns label="用户管理" modelName="user" :showAdd="true" :showDeleteBatch="false" :showFull="false" :showGroup="false"
            :table="table" :selected="selected" :importing="importing" :exporting="exporting"
            :importExcelUrlFull="importExcelUrlFull" :columns="columns" @groupChange="groupChange"
            @add="add" @importExcel="importExcel" @exportExcel="exportExcel" @showConfirm="showConfirm"
            :showImport="false" :showExport="false"/>
        </template>
        <template #body-cell-companyId="props">
          <q-td key="companyId" :props="props">
            {{getDictLabel(sysCompany,props.row.companyId) }}
          </q-td>
        </template>
        <template #body-cell-avatar="props">
          <q-td key="avatar" :props="props">
            <q-avatar v-if="props.row.avatar">
              <img style="width: 30px;height: 30px;" :src="imagePath(props.row.avatar)" />
            </q-avatar>
          </q-td>
        </template>
        <template #body-cell-sex="props">
          <q-td key="sex" :props="props">{{getDictLabel(sex,props.row.sex) }}</q-td>
        </template>
        <template #body-cell-status="props">
          <q-td key="status" :props="props">{{getDictLabel(userStatus,props.row.status) }}</q-td>
        </template>
        <template #body-cell-delFlag="props">
          <q-td key="delFlag" :props="props">{{getDictLabel(delFlag,props.row.delFlag) }}</q-td>
        </template>
        <template #body-cell-activitiSync="props">
          <q-td
            key="activitiSync"
            :props="props"
          >{{getDictLabel(activitiSync,props.row.activitiSync) }}</q-td>
        </template>
        <template #body-cell-officeId="props">
          <q-td key="sysDeptCode" :props="props">{{getDictLabel(sysDepart,props.row.sysDeptCode) }}</q-td>
        </template>
        <template #body-cell-post="props">
          <q-td key="post" :props="props">{{getDictLabel(sysPosition,props.row.post) }}</q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <cc-btn label="重置密码" color="primary" icon="mdi-key" @click="change(props.row)">
              <q-tooltip>重置密码</q-tooltip>
            </cc-btn>
            <cc-btn
              label="分配角色"
              color="primary"
              icon="engineering"
              @click="editUserRole(props.row)"
            >
              <q-tooltip>分配角色</q-tooltip>
            </cc-btn>
            <cc-btn  label="编辑" color="primary" icon="edit" @click="edit(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </cc-btn>
            <btn-del label="用户表" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <cc-dialog ref="changePassWord" title="修改密码" @submit="changePassWord">

          <div class="col-12">
            <h5>用户账号：</h5>
            <q-input outlined readonly dense v-model="selectUser.username" />
          </div>
          <div class="col-12">
            <h5>用户姓名：</h5>
            <q-input outlined readonly dense v-model="selectUser.realname" />
          </div>

          <div class="col-6">
            <h5>
              <q-icon name="star" color="red" />密码：
            </h5>
            <q-input
              outlined
              dense
              type="password"
              v-model="password"
              :rules="[v => !!v || '不可以为空']"
            />
          </div>
          <div class="col-6">
            <h5>
              <q-icon name="star" color="red" />确认密码：
            </h5>
            <q-input
              outlined
              dense
              type="password"
              v-model="confirmpassword"
              :rules="[v => !!v || '不可以为空']"
              :error="!isValid"
            >
              <template v-slot:error>两次输入密码不一致！</template>
            </q-input>
          </div>
      </cc-dialog>
    <cc-dialog ref="dialog" :title="`${editType}公司管理员`" @submit="submitBefore">
      <div class="col-6">
        <h5>
          <q-icon name="star" color="red" />登录账号：
        </h5>
        <q-input
          outlined
          dense
          debounce="500"
          hide-bottom-space
          v-model="form.username"
          type="text"
          lazy-rules
          :rules="[requiredTest]"
          @blur="checkUserName"
          :readonly="editType === '编辑'"
          autogrow
        />
      </div>
      <div class="col-6">
        <h5>
          <q-icon name="star" color="red" />姓名：
        </h5>
        <q-input
          outlined
          dense
          square
          clearable
          v-model="form.realname"
          type="text"
          :rules="[requiredTest]"
        />
      </div>
      <div class="col-6">
        <h5>电话：</h5>
        <q-input outlined dense square clearable v-model="form.phone" type="text" />
      </div>

      <div class="col-6">
        <h5>状态：</h5>
        <q-select
          outlined
          dense
          emit-value
          v-model="form.status"
          map-options
          :options="userStatus"
        />
      </div>
    </cc-dialog>

    <listselect
      ref="listselectDialog"
      :unselectedList="unselectedRoleList"
      :selectList="selectedRoleList"
      :msg="selectTitle"
      @saveSelect="setRoles"
    />
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <cc-loading :loading="loading"/>
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import listselect from 'components/listselect';
import { requiredTest, hcodeTest } from 'boot/inputTest';

export default {
  name: 'SysUser',
  mixins: [IndexMixin],
  components: {
    confirm,
    listselect,
    /* tree, */
  },
  data() {
    return {
      imageFullPath: '',
      showQuery: true,
      tableLabel: '展开',
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.BASE_URL}/sys/common/upload`,
      imgUrl: `${process.env.BASE_URL}/sys/common/static`,
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
          headerClasses: 'cc-table-index',
        },
        {
          name: 'username', align: 'center', label: '账号', field: 'username',
        },
        {
          name: 'realname', align: 'center', label: '姓名', field: 'realname',
        },
        {
          name: 'phone', align: 'center', label: '电话', field: 'phone',
        },
        {
          name: 'status', align: 'center', label: '状态', field: 'status',
        },
        {
          name: 'opt', align: 'center', label: '操作', field: 'opt',
        },
      ],
      dutyList: [],
      sex: [{ value: 1, label: '男' }, { value: 2, label: '女' }],
      userStatus: [{ value: 1, label: '正常' }, { value: 2, label: '冻结' }],
      delFlag: [{ value: '0', label: '正常' }, { value: '1', label: '已删除' }],
      activitiSync: [{ value: '1', label: '同步' }, { value: '0', label: '不同步' }],
      sysUser: [],

      sysPosition: [],
      sysCompany: [],
      selectUser: {},
      subSysCode: [],
      password: '',
      idCard: '',
      accounttype: [],
      confirmpassword: '',
      selectTitle: '',
      roleList: [],
      unselectedRoleList: [],
      selectedRoleList: [],
      sysDept: [],
      sysDeptName: null,
      sysOrg: [],
      subSys: [],

      sysPostsDuty: [],
      postName: null,
      companyName: null,
      url: {
        list: '/sys/user/list',
        add: '/sys/user/addAdmin',
        edit: '/sys/user/edit',
        delete: '/sys/user/delete',
        deleteBatch: '/sys/user/deleteBatch',
        exportXlsUrl: '/sys/user/exportXls',
        importExcelUrl: '/sys/user/importExcel',
        setUserRoles: '/sys/user/setUserRoles',
      },
    };
  },
  methods: {
    requiredTest,
    hcodeTest,
    getDictLabel,
    sysDeptCodeInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.sysDeptName = '';
        v.forEach((id) => {
          const opt = this.sysDept.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.sysDeptName = nameArray.join(',');
        });
      } else {
        const opt = this.sysDept.find((o) => o.value === v);
        this.form.sysDeptName = opt ? opt.label : '';
      }
    },

    sysPostInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.postName = '';
        v.forEach((id) => {
          const opt = this.sysPosition.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.postName = nameArray.join(',');
        });
      } else {
        const opt = this.sysPosition.find((o) => o.value === v);
        this.form.postName = opt ? opt.label : '';
      }
    },

    companyIdInput(v, row, editAfter) {
      // 这里给名称字段赋值
      if (v instanceof Array) {
        const nameArray = [];
        this.form.companyName = '';
        v.forEach((id) => {
          const opt = this.sysCompany.find((o) => o.value === id);
          if (opt) {
            nameArray.push(opt.label);
          }
          this.form.companyName = nameArray.join(',');
        });
      } else {
        const opt = this.sysCompany.find((o) => o.value === v);
        this.form.companyName = opt ? opt.label : '';
      }
    },

    addBefore() {
      this.dutyList = [];
      this.subSysCode = [];
      this.imageFullPath = '';
      if (this.form.sysDeptCode) {
        this.sysDeptCodeInput(this.form.sysDeptCode);
      }
      if (this.form.post) {
        this.sysPostInput(this.form.post);
      }
      if (this.form.companyId) {
        this.companyIdInput(this.form.companyId);
      }
      this.form = {
        status: 1,
        password: '123456',
      };

      return true;
    },
    submitBefore() {
      this.form.dutyIds = this.dutyList.join(',');
      const nameArray = [];
      this.form.dutyNames = '';
      this.dutyList.forEach((id) => {
        const opt = this.sysPostsDuty.find((o) => o.value === id);
        if (opt) {
          nameArray.push(opt.label);
        }
        this.form.dutyNames = nameArray.join(',');
      });
      this.submit();
    },
    checkUserName() {
      if (this.form.username) {
        this.$axios.get(`/sys/user/checkUserName?username=${this.form.username}&id=${this.form.id}`).then((r) => {
          if (r.result) {
            this.form.username = '';
            this.$error('账号已经存在！');
          }
        });
      }
    },
    checkIdCard() {
      if (this.form.idCard) {
        this.$axios.get(`/sys/user/checkIdCard?idCard=${this.form.idCard}&id=${this.form.id}`).then((r) => {
          if (r.result) {
            this.form.idCard = '';
            this.$error('身份证号已经存在！');
          }
        });
      }
    },
    editAfter() {
    },
    editBefore(p) {
      if (p.dutyIds && p.dutyIds.length > 0) {
        this.dutyList = p.dutyIds.split(',');
      } else {
        this.dutyList = [];
      }
      this.imageFullPath = this.imagePath(p.avatar);

      return true;
    },
    selectCatalog(n) {
      this.sysDeptCode = n.id;
      this.query();
    },
    queryParam() {
      return {
        sysDeptCode: this.sysDeptCode,
        isAdmin: 0,
        type: 3,
      };
    },
    importAvatar() {
      this.$refs.avatarUploader.pickFiles();
    },
    importedAvatar({ xhr }) {
      const response = JSON.parse(xhr.responseText);
      if (response.success) {
        this.form.avatar = response.message;
        this.imageFullPath = this.imagePath(this.form.avatar);
        this.$q.notify('上传成功');
      } else {
        this.$q.notify({
          color: 'red',
          message: '上传失败',
        });
      }
      this.$refs.avatarUploader.removeUploadedFiles();
    },
    imagePath(src) {
      let path = '';
      if (src) {
        if (src.startsWith('http')) {
          return src;
        }
        path = `${this.imgUrl}/${src}`;
      }
      return path;
    },
    show() {
      this.showQuery = true;
      this.tableLabel = '收起';
    },
    hide() {
      this.showQuery = false;
      this.tableLabel = '展开';
    },
    initDict() {
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysPosition').then((r) => {
        this.sysPosition = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysUser').then((r) => {
        this.sysUser = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysRole').then((r) => {
        this.roleList = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDictCode?dictCode=accountType').then((r) => {
        this.accounttype = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=sysPosition').then((r) => {
        this.sysPostsDuty = r;
      });
      this.$axios.get('/sys/depart/getSysOrgCode?deptType=dept').then((r) => {
        this.sysDept = r;
      });
      this.$axios.get('/sys/org/getOrgCodeName').then((r) => {
        this.sysOrg = r;
      });
      this.$axios.get('/sys/dictItem/selectItemsByDefId?defId=subSys').then((r) => {
        this.subSys = r;
      });
      this.$axios.get('/sys/company/getCompanyName').then((r) => {
        this.sysCompany = r;
      });
    },
    change(row) {
      this.password = '';
      this.confirmpassword = '';
      this.selectUser = row;
      this.$refs.changePassWord.show();
    },
    changePassWord() {
      this.$axios.put('/sys/user/changePassword', {
        confirmpassword: this.confirmpassword,
        password: this.password,
        username: this.selectUser.username,
      }).then((r) => {
        this.$info(r.message);
        this.$refs.changePassWord.hide();
      });
    },
    editUserRole(row) {
      this.selectUser = row;
      const { userRoleIdList } = row;
      this.unselectedRoleList = [];
      this.selectedRoleList = [];
      this.selectTitle = `用户[${row.realname}]分配角色`;
      this.roleList.forEach((role) => {
        if (userRoleIdList.includes(role.value)) {
          this.selectedRoleList.push(role);
        } else {
          this.unselectedRoleList.push(role);
        }
      });
      this.$refs.listselectDialog.show();
    },
    setRoles(roleList) {
      const selectedRoles = [];
      if (roleList && roleList.length > 0) {
        roleList.forEach((role) => {
          selectedRoles.push(role.value);
        });
      }
      this.$axios.put(`${this.url.setUserRoles}?userId=${this.selectUser.id}&selectedRoles=${selectedRoles.join(',')}`)
        .then((r) => {
          if (r.success) {
            this.$refs.listselectDialog.hide();
            this.query();
          }
          this.$info(r.message);
        });
    },

  },
  mounted() {
    this.initDict();
  },
  computed: {
    isValid() {
      return this.confirmpassword === this.password;
    },
  },
};
</script>
<style lang="stylus"></style>
